#!/usr/bin/env bash

if [[ "$1" == "-f" ]]; then
    if command -v trash &>/dev/null; then
        trash "$NDK/ndk-build-toolchain"
    else
        rm -rf "$NDK/ndk-build-toolchain"
    fi

    unset NDK_STANDALONE_TOOLCHAIN
fi

if [[ "$NDK_STANDALONE_TOOLCHAIN" == "" ]]; then

    if [[ "$NDK" == "" ]]; then
        echo "You should set the NDK variable to your ndk-dir!"
        exit 1
    fi

    export NDK_STANDALONE_TOOLCHAIN=$NDK/ndk-build-toolchain

    if [[ ! -d "$NDK_STANDALONE_TOOLCHAIN" ]]; then

        NDK_VER=$(grep -i revision "$NDK/source.properties")

        NDK_VER="${NDK_VER/* /}"
        echo "NDK_VER=$NDK_VER"

        NDK_MAJOR_VER="${NDK_VER/.*/}"
        echo "NDK_MAJOR_VER=$NDK_MAJOR_VER"

        if [[ "$NDK_MAJOR_VER" -ge 23 ]]; then
            # NDK23 and later does not support 'standardalone-toolchain'
            # according to <https://developer.android.com/ndk/guides/other_build_systems > export directly
            echo "NDK23 and later does not support 'standardalone-toolchain', export directly"
            if [[ $(uname -s) == "Darwin" ]]; then
                export NDK_STANDALONE_TOOLCHAIN="$NDK/toolchains/llvm/prebuilt/darwin-x86_64"
            elif [[ $(uname -s) == "Linux" ]]; then
                export NDK_STANDALONE_TOOLCHAIN="$NDK/toolchains/llvm/prebuilt/linux-x86_64"
            else # windows (没啥意义)
                export NDK_STANDALONE_TOOLCHAIN="$NDK/toolchains/llvm/prebuilt/windows-x86_64"
            fi
            pushd .
            cd $NDK && ln -snf "$NDK_STANDALONE_TOOLCHAIN" ndk-build-toolchain
            popd
        else
            $NDK/build/tools/make-standalone-toolchain.sh --toolchain=arm-linux-android-clang3.6 --arch=arm --platform=android-26 --install-dir=$NDK_STANDALONE_TOOLCHAIN --stl=libc++
        fi
    fi
fi

echo "NDK_STANDALONE_TOOLCHAIN=$NDK_STANDALONE_TOOLCHAIN"
